<?php
session_start();
include("d:/shante/myzhuaqu.php");
require_once('d:/shante/vendor/autoload.php');
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverWait;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Facebook\WebDriver\WebDriverJavascriptExecutor;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\Remote\RemoteWebElement;

global $driver;
//$cookiestr=getDouyinCookie();

if($_REQUEST['cookie']!=""){
    $cookiestr=$_REQUEST['cookie']=trim(preg_replace("/cookie:\s*/i","",$_REQUEST['cookie']));
    file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/shopee.txt",$_REQUEST['cookie']);
}
$url = $_REQUEST['url'];
gotoShopeeNewGoods();

function gotoShopeeNewGoods(){
    global $driver,$argv;

    if($_REQUEST['item_id']==""){
        if(preg_match("/https?\:\/\/shop\.shante\.me\/Item\/detail\/id\/([0-9]+)\.html/Uisx",$_POST["s_url"],$nn)){
            $_REQUEST['item_id']=$nn[1];
        }elseif(preg_match("/https?\:\/\/shop\.shante\.me\/Shop\/Item\/edit\/id\/([0-9]+)\.html/Uisx",$_POST["s_url"],$nn)){
            $_REQUEST['item_id']=$nn[1];
        }
    }

    $_SESSION['item_id']=$_REQUEST['item_id']?$_REQUEST['item_id']:$argv[1];
    $json=file_get_contents("https://shop.shante.me/yunshop/au3/getdata.php?item_id={$argv[1]}&json=true&t=".time());  //438
    $data=json_decode($json,1);
    $nn=explode(">",$data["category4"]);

    //关闭多移窗口
//    $output = array();
//    $return_var = 0;
//    exec('tasklist | findstr "chrome.exe"', $output, $return_var);
//    if ($return_var === 0) {
//        foreach ($output as $line) {
//            echo $line . PHP_EOL;
//            if (preg_match('/^chrome.exe\s*(\d+)\s+.*/', $line, $matches)) {
//                $pid = $matches[1];
//                $command = "taskkill /F /PID $pid"; // /F 表示强制终止进程
//                exec($command, $output, $return_var);
//            }
//        }
//    } else {
//        echo "Error executing command: " . $return_var . PHP_EOL;
//    }

    $options = new ChromeOptions();
    //$options->addArguments(['--headless']);  //不出现浏览器
    $options->addArguments(['--disable-blink-features=AutomationControlled']);
    $options->addArguments(['--disable-extensions']);
    $options->addArguments(['--disable-gpu']);
    $options->addArguments(['--disable-infobars']);
    $options->addArguments(['--disable-notifications']);
    $options->addArguments(['--disable-popup-blocking']);
    $options->addArguments(['--disable-web-security']);
    $options->addArguments(['--ignore-certificate-errors']);
    $options->addArguments(['--no-sandbox']);
    $options->setExperimentalOption("useAutomationExtension", false);
    $options->setExperimentalOption("excludeSwitches", ['enable-automation']);
    $options->addArguments(['--user-data-dir=/d/temp']);
    //exec("taskkill /IM chrome.exe /F");


    if ($driver !== null) {
        $driver->quit();
        $driver = null;
    }

    $capabilities = DesiredCapabilities::chrome();
    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
    $driver = RemoteWebDriver::create('http://localhost:9515', $capabilities);
    $url="https://seller.shopee.cn/portal/product/mtsku/new?item_id={$_SESSION['item_id']}";
    $driver->get($url);
    $wait = new WebDriverWait($driver, 5);

//    $cookieString = file_get_contents("d:/wwwroot/www/shop/yunshop/cookie/shopee.txt");
//    $cookies = explode(';', $cookieString);
//    foreach ($cookies as $cookie) {
//        list($name, $value) = explode('=', $cookie, 2);
//        if ($name != null && trim($name) != "") {
//            $cookieObj = new Cookie(trim($name), trim($value));
//            $driver->manage()->addCookie($cookieObj);
//        }
//    }
//    $driver->get("https://seller.shopee.cn/portal/product/mtsku/new?item_id={$_SESSION['item_id']}");
//    $wait = new WebDriverWait($driver, 5);
//    $wait->until(
//        function ($driver) {
//            return strpos($driver->getCurrentUrl(), 'product/mtsku') !== false;
//        }
//    );
    $cookies = $driver->manage()->getCookies();
    $cookiestr = "";
    for ($i = 0; $i < count($cookies); $i++) {
        $cookiestr .= $cookies[$i]->getName() . "=" . $cookies[$i]->getValue() . ";";
    }
    file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/shopee.txt", $cookiestr);

    try {
        $wait->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//div[@class, 'basic-info-title')]"))
        );
    }catch (Exception $e){
        $wait = new WebDriverWait($driver, 120);
        try {
            $wait->until(
                WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//div[@class, 'username-item')]"))
            );
            echo 111;
        }catch (Exception $e){

        } finally {
            $wait = new WebDriverWait($driver, 120);
            try {
                $wait->until(
                    WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::cssSelector(".basic-info-title"))
                );
            }catch (Exception $e){
                echo $e;
            }
        }
    }




    //选择类目
    sleep(1);
    $nn=explode(">",$data["category4"]);
    $driver->executeScript('document.querySelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div.edit-row.is-last-edit-row > div.edit-row-right-full > div.product-category > div > div > div > div > div > div > span").click()');
    $wait = new WebDriverWait($driver, 10);
    try {
        for($i=0;$i<count($nn);$i++) {
            $element = $wait->until(
                WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//ul[@class='scroll-item'][".($i+1)."]//p[contains(text(), '{$nn[$i]}')]"))
            );
            $actions = new WebDriverActions($driver);
            $actions->moveToElement($element)->perform();
            sleep(1);
            $element->click();
            $driver->findElements(WebDriverBy::xpath("//ul[@class='scroll-item']//p[contains(text(), '{$nn[0]}')]"));
        }
        sleep(2);
        $driver->executeScript('document.querySelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div.edit-row.is-last-edit-row > div.edit-row-right-full > div.product-category > div.eds-modal.product-category-selector-modal > div > div > div > div > div.eds-modal__footer.with-assist > div.eds-modal__footer-buttons > button.eds-button.eds-button--primary.eds-button--normal").click()');

    }catch(Exception $e){
        echo "加载普通商品页超时";
    }
    $data_post['cookies']=$cookiestr;
    $data_post['url']=$url;
    $json=curl_post_json("https://shante.me/public/chrome/index.php",json_encode($data_post));
    $data=json_decode($json,1);
    $temp=$data['marker'];
    $temp=preg_replace("/javascript\:\(function\(\)\{|\}\)\(\)\;\s*$/","",$temp);
    $driver->executeScript($temp);
    //商品名称
    $name=$driver->findElement(WebDriverBy::cssSelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div:nth-child(3) > div.edit-main > div > div > div > div > div > input"));
    $name->clear()->sendKeys($data["name"]);


    $driver->executeScript('document.querySelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div:nth-child(3) > div.edit-main > div > div > div > div > div > input").blur();');

    //商品描述
    $driver->executeScript('document.querySelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div.edit-row.description-wrap > div.edit-main > div > span > div > div > div > div > div.shopee-input.shopee-input__area > textarea").value="'.html(strip_tags($data["intro"])).'";');



    //上传图片
    $el = $wait->until(
        WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::cssSelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div:nth-child(1) > div.edit-main.image-offset > div > div.container > div > div > div > div> div> div "))
    );
    for($i=0;$i<count($data['images']);$i++) {
        shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\closewin.au3");
        $el->click();
        shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\upload_file.au3 {$data['images'][$i]}");
        sleep(3);
    }

    //上传视频
    if($data["video_url"]!="") {
        $el = $wait->until(
            WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::cssSelector("#app > div.full-screen-container > div > div > div > div.product-edit__main > section:nth-child(2) > div > div.panel-content-wrapper > div > div.container > div.product-video-manager.edit-row > div.edit-main > div.video-manager > div > div > div > div"))
        );
        $el->click();
        shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\upload_file.au3 {$data["video_url"]}");
        $el2 = $wait->until(
            WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::cssSelector("body > div.shopee-modal > div > div > div > div > div.shopee-modal__footer.with-assist > div.shopee-modal__footer-buttons > button.shopee-button.shopee-button--primary.shopee-button--normal"))
        );
        $el2->click();
    }

    sleep(2);

    //移动页面到商品详情位置
    $el3 = $wait->until(
        WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//div[@class='panel-title'][contains(text(),'商品属性')]"))
    );
    $el3=$driver->findElement(WebDriverBy::xpath("//div[@class='panel-title'][contains(text(),'商品属性')]"));
    $driver->executeScript("arguments[0].scrollIntoView({block: 'start'});", [$el3]);

    select($driver,"品牌","NoBrand");
    select($driver,"短款上衣","是");
    select($driver,"加大码","是");
    select($driver,"材质","棉");
    select($driver,"袖长","其他");

   //select($driver,"衣领","其他");

    $data_post = [
        'url' => "https://seller.shopee.cn/portal/product/mtsku/new?item_id={$_SESSION['item_id']}",
        's_url' => "https://shop.shante.me/Shop/Item/edit/id/{$GLOBALS['argv'][1]}.html",
        'content' => ''
    ];
    $jsonData = json_encode($data_post);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://shop.shante.me/yunshop/au3/click.php?XDEBUG_SESSION_START=5432534");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($jsonData)
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    $data3=array();
    $data3["images"]=$data["images"];
    $jsonData=json_encode($data3);
    $localurl = "http://localhost:3000/downloadimages";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $localurl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'sec-ch-ua: "Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
        'sec-ch-ua-platform: "Windows"',
        'sec-ch-ua-mobile: ?0',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Accept: */*',
        'Sec-Fetch-Site: cross-site',
        'Sec-Fetch-Mode: cors',
        'Sec-Fetch-Dest: empty',
        'Accept-Encoding: gzip, deflate, br',
        'Accept-Language: zh-CN,zh;q=0.9',
        'Content-Length: ' . strlen($jsonData)
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $content=curl_exec($ch);
    curl_close($ch);
    $script=file_get_contents('https://shop.shante.me/yunshop/au3/click.js');
    $driver->executeScript($script);
    $driver->quit();
}


function html($str){
    $str=str_replace('"','\"',$str);
    $str=preg_replace("/\n|\r/Uis",'',$str);
    return $str;
}

function select($driver,$title,$value)
{
    $wait = new WebDriverWait($driver, 10);
    $element = $wait->until(
        WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//div[@class='attribute-select-item']//*[contains(text(), '{$title}')]"))
    );
    $inputEl = $element->findElement(WebDriverBy::xpath(".."))->findElement(WebDriverBy::xpath("//div[@class='attribute-select-item']"))->findElement(WebDriverBy::xpath("//div[@class='shopee-select']"));
    $inputEl->click();
    $element2 = $wait->until(
        WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//div[@role='listitem']//*[contains(text(), '{$value}')]"))
    );
    $element2->click();
}